package com.test.ai.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 8/21/25 8:49 AM
 * @modifiedBy:
 * @version: 1.0
 */
public class FluxUtils {
  private static final Logger LOGGER = LoggerFactory.getLogger(FluxUtils.class);

  public static <T> Mono<T> revertJson(Class<T> clazz, Mono<String> mono) {
    return mono.<T>handle(
            (jsonString, sink) -> {
              LOGGER.info("接收到的json字符串响应结果为: {}", jsonString);
              final String trimThinking = ResponseUtils.removeThinkTags(jsonString);
              LOGGER.info("清理掉思考过程，准备解析json的字符串为: {}", trimThinking);
              ObjectMapper objectMapper = new ObjectMapper();
              try {
                sink.next(objectMapper.readValue(trimThinking, clazz));
              } catch (JsonProcessingException e) {
                sink.error(new RuntimeException(e));
              }
            })
        .onErrorResume(
            JsonProcessingException.class,
            e -> {
              LOGGER.error("JSON 解析失败: {}", e.getMessage());
              return Mono.error(new RuntimeException("响应格式错误，请检查模型输出"));
            });
  }
}
